package com.cqcetbbs.smartlab.cqcetbbs.fragment;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import com.cqcetbbs.smartlab.cqcetbbs.R;
import com.cqcetbbs.smartlab.cqcetbbs.activity.CampusActivity;
import com.cqcetbbs.smartlab.cqcetbbs.activity.CommunicationActivity;
import com.cqcetbbs.smartlab.cqcetbbs.activity.LocationActivity;
import com.cqcetbbs.smartlab.cqcetbbs.activity.NewsDetailActivity;
import com.cqcetbbs.smartlab.cqcetbbs.activity.SecondhandActivity;
import com.cqcetbbs.smartlab.cqcetbbs.adapter.GridViewAdapter;
import com.cqcetbbs.smartlab.cqcetbbs.adapter.SchoolNewsAdapter;
import com.cqcetbbs.smartlab.cqcetbbs.javabean.BannerInfo;
import com.cqcetbbs.smartlab.cqcetbbs.javabean.ModuleInfo;
import com.cqcetbbs.smartlab.cqcetbbs.javabean.SchoolNews;
import com.cqcetbbs.smartlab.cqcetbbs.utils.GlideImageLoader;
import com.cqcetbbs.smartlab.cqcetbbs.utils.MySnackbar;
import com.cqcetbbs.smartlab.cqcetbbs.utils.SpUtils;
import com.cqcetbbs.smartlab.cqcetbbs.view.MyGridView;
import com.cqcetbbs.smartlab.cqcetbbs.view.SchoolListView;
import com.cqcetbbs.smartlab.cqcetbbs.view.VerticalScrolledListview;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
 * Created by user on 2017/9/20.
 * 主页面
 */

public class FragmentMain extends BaseFragment {


    public static final String GET_BANNER_PATH = "http://api.cqcetlab.com/Home/banner/getban/";
    public static final String SCHOOLNEWS_PATH = "http://api.cqcetlab.com/Home/index/IndexSchoolNews";
    //保存banner页面数据（key）
    public static final String BANNER_DATA = "banner_data";
    public static final String SCHOOLNEWS = "school_news";

    //请求banner数据成功
    public static final int BANNER_SUCCESS = 1;
    public static final int SCHOOLNEWS_SUCCESS = 2;
    //请求banner数据失败
    public static final int FAIL = 0;

    View view = null;

    Toolbar tools;
    VerticalScrolledListview vsd_text;

    AppCompatActivity mAppCompatActivity;
    SchoolListView lv_SchoolNews;

    Banner banner;
    ArrayList<BannerInfo> BannerList;
    ArrayList<SchoolNews> SchoolNews_List;

    BannerInfo bannerInfo;

    GridView gv_all;
    //每行的个数
    int count = 3;

    SchoolNewsAdapter SchoolNewsAdapter;

    OkHttpClient client;
    private Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case BANNER_SUCCESS:
                    BannerList = null;
                    bannerInfo = new BannerInfo();
                    Gson gson = new Gson();
                    Type listType = new TypeToken<ArrayList<BannerInfo>>() {
                    }.getType();
                    BannerList = gson.fromJson((String) msg.obj, listType);
                    setBannerData();
                    break;
                case FAIL:
                    MySnackbar.ShowSnackbar(view, "网络异常，数据加载失败");
                    break;
                case SCHOOLNEWS_SUCCESS:
                    Gson gsonnews = new Gson();
                    Type listTypenews = new TypeToken<ArrayList<SchoolNews>>() {
                    }.getType();
                    SchoolNews_List = gsonnews.fromJson((String) msg.obj, listTypenews);
                    SchoolNewsAdapter SchoolNewsAdapter = new SchoolNewsAdapter(activity, SchoolNews_List);
                    lv_SchoolNews.setAdapter(SchoolNewsAdapter);

                    setClick();
                    break;
            }
        }
    };

    private void setClick() {

        lv_SchoolNews.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Bundle bundle = new Bundle();
                bundle.putString("id", SchoolNews_List.get((int) l).getId() + "");
                Intent intent = new Intent(activity, NewsDetailActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);

            }
        });
    }

    @Override
    public View getInitView() {

        view = View.inflate(activity, R.layout.fragment_main, null);
        //TextView textView = view.findViewById(R.id.textView);
        lv_SchoolNews = view.findViewById(R.id.lv_SchoolNews);
        banner = view.findViewById(R.id.banner);
//        sliderLayout = view.findViewById(R.id.slider);
//        indicator = view.findViewById(R.id.custom_indicator);

        Typeface mtypeface = Typeface.createFromAsset(activity.getAssets(), "mi.TTF");
        // textView.setTypeface(mtypeface);

        // vsd_text = view.findViewById(R.id.vsd_text);

        gv_all = (MyGridView) view.findViewById(R.id.gv_all);
        //设置Toolbar
        setTool();

        return view;
    }

    @Override
    public void initData() {

        SchoolNews_List = new ArrayList<SchoolNews>();
        //将数据取出
        String data = SpUtils.getStringValues(activity, BANNER_DATA, null);
        String newsdata = SpUtils.getStringValues(activity, SCHOOLNEWS, null);
        if (!TextUtils.isEmpty(data)) {
            Message msg = mhandler.obtainMessage(BANNER_SUCCESS, data);
            mhandler.sendMessage(msg);
        }
        if (!TextUtils.isEmpty(newsdata)) {
            Message msg = mhandler.obtainMessage(SCHOOLNEWS_SUCCESS, newsdata);
            mhandler.sendMessage(msg);
        }
        //请求（okhttp）数据并显示
        getBannerData(4);
        getData();
        addPlate();

    }


    @Override
    public void onResume() {
        super.onResume();
        getData();

    }

    //设置Banner页面的内容
    private void setBannerData() {
        //  Log.e("BannerList.size()", BannerList.size() + "");

        ArrayList<String> BannerTtile = new ArrayList<>();
        ArrayList<String> Bannerpic = new ArrayList<>();

//        BannerTtile.add(0,"Club");
//        BannerTtile.add(0,"job");
//        BannerTtile.add(0,"life");
//        BannerTtile.add(0,"study");
//        BannerTtile.add(0,"trade");
//        Bannerpic.add(0,bannerInfo.getClub());
//        Bannerpic.add(1,bannerInfo.getJob());
//        Bannerpic.add(2,bannerInfo.getLife());
//        Bannerpic.add(3,bannerInfo.getStudy());
//        Bannerpic.add(4,bannerInfo.getTrade());

        for (int i = 0; i < BannerList.size(); i++) {
            BannerTtile.add(i, BannerList.get(i).getId());
            Bannerpic.add(i, BannerList.get(i).getPic());
        }
        //默认是CIRCLE_INDICATOR
        banner.setImages(Bannerpic)
                .setBannerTitles(BannerTtile)
                .setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE)
                .setImageLoader(new GlideImageLoader())
                .start();

//
//        sliderLayout.removeAllSliders();
//        Log.e("BannerList.size()", BannerList.size() + "");
//        for (int i = 0; i < BannerList.size(); i++) {
//            //新建三个展示View，并且添加到SliderLayout
//
//            TextSliderView tsv = new TextSliderView(activity);
//            tsv.image((BannerList.get(i).getPic()))
//                    .description(BannerList.get(i).getId());
//            sliderLayout.addSlider(tsv);
//        }
//
//        //对SliderLayout进行一些自定义的配置
//
//        //文字的动画
//        sliderLayout.setCustomAnimation(new DescriptionAnimation());
//
//        //图片的动画
//        sliderLayout.setPresetTransformer(SliderLayout.Transformer.Default);
//        sliderLayout.setDuration(3000);
//        //sliderLayout.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
//        sliderLayout.setCustomIndicator(indicator);

//        //最新消息内容s
//        vsd_text.setData(descriptions);

    }


    //
    public void addPlate() {
        ModuleInfo b1 = new ModuleInfo(R.drawable.trade, "二手交易", "https://www.baidu.com/");
        ModuleInfo b2 = new ModuleInfo(R.drawable.campus, "校园快讯", "https://www.baidu.com/");
        ModuleInfo b3 = new ModuleInfo(R.drawable.navigation, "校园导航", "https://www.baidu.com/");
        ModuleInfo b4 = new ModuleInfo(R.drawable.learn, "交流学习", "https://www.baidu.com/");
        ModuleInfo b5 = new ModuleInfo(R.drawable.more_, "待定模块", "https://www.baidu.com/");

        final ArrayList<ModuleInfo> ModuleInfoList = new ArrayList<ModuleInfo>();
        ModuleInfoList.add(b1);
        ModuleInfoList.add(b2);
        ModuleInfoList.add(b3);
        ModuleInfoList.add(b4);
        ModuleInfoList.add(b5);

        GridViewAdapter gridViewAdapter = new GridViewAdapter(activity, ModuleInfoList);
        gv_all.setAdapter(gridViewAdapter);

        gv_all.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                switch (i) {
                    case 0:
                        startActivity(new Intent(activity, SecondhandActivity.class));
                        break;
                    case 1:
                        startActivity(new Intent(activity, CampusActivity.class));
                        break;
                    case 2:
                        startActivity(new Intent(activity, LocationActivity.class));
                        break;
                    case 3:
                        startActivity(new Intent(activity, CommunicationActivity.class));
                        break;
                    case 4:
                        Toast.makeText(activity, ModuleInfoList.get(i).desc, Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });

    }


    //设置Toolbar
    public void setTool() {
        tools = view.findViewById(R.id.tools);
        mAppCompatActivity = (AppCompatActivity) activity;
        mAppCompatActivity.setSupportActionBar(tools);
        ActionBar actionBar = mAppCompatActivity.getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(false);
        }

        tools.setTitle("");
    }


    //请求Banner页面的数据
    private void getBannerData(final int num) {
        client = new OkHttpClient();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Request request = new Request.Builder()
                        .get()
                        .url(GET_BANNER_PATH + "num" + num)
                        .build();
                //新建一个线程，用于得到服务器响应的参数
                Response response = null;
                try {
                    //回调
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui
                        String result = response.body().string();
                        //将数据保存
                        SpUtils.setStringValues(activity, BANNER_DATA, result);
                        Message msg = mhandler.obtainMessage(BANNER_SUCCESS, result);
                        mhandler.sendMessage(msg);
                    }
                } catch (IOException e) {

                    Message msg = mhandler.obtainMessage(FAIL);
                    mhandler.sendMessage(msg);
                    e.printStackTrace();
                }
            }
        }).start();

    }


    //主页校园新闻
    private void getData() {
        client = new OkHttpClient();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Request request = new Request.Builder()
                        .get()
                        .url(SCHOOLNEWS_PATH)
                        .build();
                Response response = null;
                try {
                    //回调
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui
                        String result = response.body().string();
                        //将数据保存
                        SpUtils.setStringValues(activity, SCHOOLNEWS, result);
                        Message msg = mhandler.obtainMessage(SCHOOLNEWS_SUCCESS, result);
                        mhandler.sendMessage(msg);
                    }
                } catch (IOException e) {

                    Message msg = mhandler.obtainMessage(FAIL);
                    mhandler.sendMessage(msg);
                    e.printStackTrace();
                }
            }
        }).start();

    }
}
